from mootdx.utils import holiday
import datetime  as dt
import redis
import configparser
import pickle
import logging
import time
import os
import akshare as ak
import pandas as pd

import setproctitle
# setproctitle.setproctitle("check_trade_time")

process_id = os.getpid()

log_format = f"%(asctime)s - %(levelname)s - PID:{process_id} - %(filename)s:%(lineno)d - %(message)s"
date_format = "%Y-%m-%d %H:%M:%S"  # 精确到秒
logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=date_format)


# 初始化配置解析器
config = configparser.ConfigParser()

# 读取配置文件
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
config.read(current_dir+'/config.ini')

# 获取Redis的配置信息
redis_host = config.get('Redis', 'host')
redis_port = config.getint('Redis', 'port')
redis_db = config.getint('Redis', 'db')
redis_password = config.get('Redis', 'password')
r = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password)


# 0是非工作日
# 1是工作日
def isholiday():
    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    current_date = dt.datetime.now()
    formatted_date = current_date.strftime('%Y-%m-%d')
    date_to_check = pd.to_datetime(formatted_date)
    tool_trade_date_hist_sina_df['trade_date'] = pd.to_datetime(tool_trade_date_hist_sina_df['trade_date'])
    is_trading_day = date_to_check in tool_trade_date_hist_sina_df['trade_date'].values
    return is_trading_day

is_working_day = isholiday()
print(is_working_day)
def is_trade_time():
    
    if not is_working_day:
        logging.debug("当前非工作日")
        r.set("is_trade_time", "NO")
        return
    
    now = dt.datetime.now().time()  # 获取当前时间
    morning_start = now.replace(hour=9, minute=25, second=1, microsecond=0)
    morning_end = now.replace(hour=11, minute=30, second=1, microsecond=0)
    afternoon_start = now.replace(hour=12, minute=59, second=59, microsecond=0)
    afternoon_end = now.replace(hour=15, minute=0, second=1, microsecond=0)

    if morning_start <= now <= morning_end or afternoon_start <= now <= afternoon_end:
        # logging.debug("当前时间在指定时间范围内")
        r.set("is_trade_time", "YES")
    else:
        logging.debug("不在交易时间内")
        r.set("is_trade_time", "NO")
    
    
if __name__ == "__main__":
    while True:
        try:
            start_time = time.time()
            is_trade_time()
            end_time = time.time()
            elapsed_time = end_time - start_time
            sleep_time = max(1 - elapsed_time, 0)
            time.sleep(sleep_time)
        except Exception as e:
            logging.error(e)
            time.sleep(1)
        